﻿using System;
using System.ServiceModel;

namespace Needle.Bus.Transport.Impl.WCF
{

    public class WCFEndPoint<T> : IChannel<T>
    {

        ITransport _Owner;

        public WCFEndPoint(string topic)
        {
            _Topic = topic;
        }

        #region IChannel<T> Members

        private string _Topic;
        public string Topic
        {
            get { return _Topic; }
        }

        public void Send(T message)
        {
            foreach (IEndPoint<T> endpoint in _Owner.Extensions.FindAll<IEndPoint<T>>())
                if (endpoint.Topic == _Topic)
                    endpoint.Receive(message);
        }

        #endregion

        #region IExtension<ITransport> Members

        void IExtension<ITransport>.Attach(ITransport owner)
        {
            if (_Owner != null)
                throw new InvalidOperationException("already attached to owner");
            _Owner = owner;
        }

        void IExtension<ITransport>.Detach(ITransport owner)
        {
            if (_Owner != owner)
                throw new InvalidOperationException("wrong owner");
            _Owner = null;
        }

        #endregion

    }
}
